//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.goldcn.Interceptor;

import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;


public class ErpInterceptor implements HandlerInterceptor {

    private static ApplicationContext applicationContext;

    public ErpInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        SystemContext.setRequest(request);
        SystemContext.setResponse(response);
        try {
            if(!request.getMethod().equals("OPTIONS")) {
                String token = request.getHeader("token");
                    if(token == null ) {
                    CurrentUser user = getTempCurrentUser(token);
                    request.setAttribute("user", user);
                    return true;
                }
                CurrentUser user = getCurrentUser(token);
                request.setAttribute("user", user);
                RedisService redisService = (RedisService)applicationContext.getBean("redisService");
                String serviceToekn = redisService.load(user.getTokenId());
                if(serviceToekn == null || !serviceToekn.equals(token)) {
                    this.loginError(response);
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SystemContext.removeAll();

        CurrentUser user = (CurrentUser)request.getAttribute("user");
        if(user == null){
            return;
        }
        String url = request.getRequestURI();
        String reqMethod = request.getMethod();
        RedisService redisService = (RedisService)applicationContext.getBean("redisService");
    }

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    private CurrentUser getCurrentUser(String token){
        String userInfo = token.substring(token.indexOf(46), token.lastIndexOf(46));
        userInfo = StringUtils.newStringUtf8(Base64.decodeBase64(userInfo.getBytes()));
        JSONObject jsStr = JSONObject.fromObject(userInfo);
        CurrentUser user = new CurrentUser();
        user.setUserID(jsStr.get("userID").toString());
        user.setUserName(jsStr.get("userName").toString());
        user.setChinaName(jsStr.get("chinaName").toString());
        user.setRolesID(jsStr.get("rolesID").toString());
        user.setTokenId(jsStr.get("tokenId") != null ? jsStr.get("tokenId").toString() : "");
        return user;
    }

    private CurrentUser getTempCurrentUser(String token){
      /*  String userInfo = token.substring(token.indexOf(46), token.lastIndexOf(46));
        userInfo = StringUtils.newStringUtf8(Base64.decodeBase64(userInfo.getBytes()));
        JSONObject jsStr = JSONObject.fromObject(userInfo);*/
        CurrentUser user = new CurrentUser();
        user.setUserID("D135405E-12C9-4570-AA24-CC58FD900DCA");
        user.setUserName("admin");
        user.setChinaName("admin");
        user.setRolesID("1");
        /*user.setTokenId(jsStr.get("tokenId") != null ? jsStr.get("tokenId").toString() : "");*/
        return user;
    }

    /**
     * token失效响应
     * @param response
     * @throws IOException
     */
    private void loginError(HttpServletResponse response) throws IOException {
        HashMap dataResult = new HashMap();
        dataResult.put("code", "101");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(JSONObject.fromObject(dataResult).toString());
    }

    /**
     * 没有权限响应
     * @param response
     * @throws IOException
     */
    private void noPermissions(HttpServletResponse response) throws IOException {
        HashMap dataResult = new HashMap();
        dataResult.put("code", "100");
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(JSONObject.fromObject(dataResult).toString());
    }
}
